﻿/*
SharpContent
Copyright (c) 2002-2009, State of Montana

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the State of Montana nor the names of contributors may be used to endorse
or promote products derived from this software without specific prior
written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
*/
(function() {
	// HACK: Tightly coupled to name of Previous directory link in folder
	this.sortItemListing = function(a, b) {
		// // If children aren't there for whatever reason (e.g. in FF <3.5)
		// if (!a.children && !b.children)
			// return 0;

		// var achild = a.children[0];
		// var bchild = b.children[0];
		var atext = a.firstChild.nextSibling.innerHTML.toLowerCase();
		var btext = b.firstChild.nextSibling.innerHTML.toLowerCase();

		// sort but ignore the Previous Directory node
		if (atext == "previous directory")
			return -1;
		if (btext == "previous directory")
			return 1;
		if (atext < btext)
			return -1;
		if (atext > btext)
			return 1;
		if (atext == btext)
			return 0;
	};

	// Global registry
	// TODO: Remove widgets and anything else that doesn't belong here... panes and actions are configurable so they remain.
	this.sharpRegistry = {
		'actions': new Hash(),
		'panes': new Hash(),
		'widgets': new Hash(),
		'itemSpecifications': new Hash(),
		'breadcrumbs': new Array(),
		'activePanes': {
			'folder': null,
			'item': null
		}
	};

	this.showBreadCrumbs = function(elementId) {
		var element = document.id(elementId);
		if (element) {
			element.set('text', makeBreadCrumbs());
		}
	}

	this.makeBreadCrumbs = function() {
		var text = "";
		this.sharpRegistry.breadcrumbs.each(function(crumb){
			if (crumb) 
			text += " / " + crumb
		});
		return text;
	}

	this.updateBreadCrumbs = function(url) {
		host = window.location.hostname;
		pathSegments = url.slice(url.lastIndexOf(host) + host.length + 1).split('/')
		this.sharpRegistry.breadcrumbs = pathSegments;
	}

	var window = this, sharpcontent = window.sharpcontent = {
		getPane: function(url, item, displayElementId) {
			var baseItem = sharplib.getBaseItemDav(item);
			var resourceProvider = baseItem.getElementsByTagName('mc:resourceprovider')[0];
			var pid = resourceProvider.textContent ? resourceProvider.textContent : resourceProvider.text;
			var mimeType = sharplib.getItemMimeType(baseItem);
			
			if (sharpRegistry.panes[pid]
				&& sharpRegistry.panes[pid][mimeType]) {
				return new sharpRegistry.panes[pid][mimeType](url, item, displayElementId);
			} else {
				if (mimeType == "application/x-folder") {
					return new sharpRegistry.panes["default.folder"](url, item, "item-listing-div");
				}
				else {
					return new sharpRegistry.panes["default.item"](url, item, displayElementId);
				}
			}
		},
		resize: function() {
			if (sharpRegistry.activePanes['item'])
				sharpRegistry.activePanes['item'].resize();
			if (sharpRegistry.activePanes['folder'])
				sharpRegistry.activePanes['folder'].resize();
			if (sharpRegistry.activePanes['table'])
				sharpRegistry.activePanes['table'].resize();
		},
		sharpBrowser: function() {
			var self = this;
			this.currentItemId = undefined;
			this.state = undefined;
			this.retriedUrls = new Hash();
			var openCallback = function(result, url, representation) {
				var item = result;
				if (item) {
					// have to register the individual items in the folderPane
					try {					
						pane = sharpcontent.getPane(url, item, "content");
						
						if (sharpbar.browser.retriedUrls.has(url))
							delete sharpbar.browser.retriedUrls[url];
						
						pane.display();
					} catch (e) {
						if (e.name == 'ItemSpecificationException' && !sharpbar.browser.retriedUrls.has(url)) {
							sharpbar.browser.retriedUrls[url] = true;
							sharpbar.browser.openByUrl(url);
						}
					}
				}
			};

			this.openByUrl = function(url, queryoptions, callbackOverride, folderOnly) {
				//console.log(url);
				callback = callbackOverride ? callbackOverride : openCallback;
				mc.propfind(url, function(results) {
					var mimeType = sharplib.getItemMimeType(results);
					
					if (folderOnly && mimeType != 'application/x-folder') {
						sharpbar.browser.openByUrl(url.slice(0, url.lastIndexOf('/')), ['D:displayname', 'mc:mimetype', 'mc:resourceprovider', 'mc:version', 'mc:published'], null, true);
					}
					else {
						callback(results, url, REPRESENTATIONS.xml);
					}
				}, true, queryoptions);
			};
		},
		sharpBar: function(opts) {
			this.options = opts;
			
			this.browser = new sharpcontent.sharpBrowser();
			
			if (this.options) {
				this.applicationUrl = this.options.applicationUrl;
				this.mediaUrl = this.options.mediaUrl;
			}
			
			this.relationshipTypeOptions = [
				'Application',
				'Host',
				'Database',
				'Database Server',
				'Dev Server',
				'Test Server',
				'Prod Server',
				'Network',
				'MAC',
				'FMM Client',
				'Service'
			];
			
			var bar = new Element('h1', { 
				id: 'application-title' 
			}).grab(new Element('a', { 
				href: '/',
				text: 'ITSD Inventory'  
			}));

			bar.inject(this.options.barTarget ? this.options.barTarget : document.body, 'top');

			var href = window.location.href;
		
			var lastChar = href.charAt(href.length - 1);
			var baseUrl =  lastChar == "#"? href.slice(0, href.length - 1) : href;
			this.browser.openByUrl(baseUrl,['D:displayname', 'mc:mimetype', 'mc:resourceprovider', 'mc:version', 'mc:published', 'mc:name']);
		}
	};
})();
